package com.secsbrain.frame.task.spring;

import com.secsbrain.frame.task.ConsoleManager;
import com.secsbrain.frame.task.ZKScheduleManager;
import com.secsbrain.frame.task.web.HomeServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableConfigurationProperties(TaskScheduleProperties.class)
public class TaskScheduleAutoConfigure {

    private static transient Logger logger = LoggerFactory.getLogger(TaskScheduleAutoConfigure.class);

    @Autowired
    private TaskScheduleProperties properties;

    @Bean(name = "zkScheduleManager",initMethod="init")
    public ZKScheduleManager zkScheduleManager(){
        ZKScheduleManager zkScheduleManager=new ZKScheduleManager();
        Map<String, String> zkConfig=new HashMap<>();
        zkConfig.put("zkConnectString", properties.getZkConnectString());
        zkConfig.put("appName", properties.getAppName());
        String rootPath=properties.getRootPath()+"/"+properties.getAppName();
        logger.debug("rootPath:{}",rootPath);
        zkConfig.put("rootPath", rootPath);
        zkConfig.put("zkSessionTimeout", properties.getZkSessionTimeout());
        zkConfig.put("userName", properties.getUserName());
        zkConfig.put("password", properties.getPassword());

        zkScheduleManager.setZkConfig(zkConfig);
        return zkScheduleManager;
    }

    @Bean(name = "schedulerFactoryBean")
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean=new SchedulerFactoryBean();
        Properties quartzProperties=new Properties();
        quartzProperties.put("org.quartz.scheduler.skipUpdateCheck", true);
        schedulerFactoryBean.setQuartzProperties(quartzProperties);
        return schedulerFactoryBean;
    }

    /**
     * 代码注册servlet(不需要@ServletComponentScan注解)
     * @return
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new HomeServlet(), "/taskSchedule/*");
    }

}
